//η φόρμα που δείχνει τους καλλιτέχνες
//author: Κωνσταντίνα Πολυχρονοπούλου
package artist;

import java.util.Iterator;
import java.util.List;
import javax.swing.JFrame;
import radiostation_POJOS.Artist;
import javax.swing.JOptionPane;
import radiostation.DBManager;
import radiostation_POJOS.Album;

public class ListArtistForm extends javax.swing.JFrame {
    //declarations
    int selectedRow;
    Artist artist;
    JFrame thisFrame;
   
    //constructor
    public ListArtistForm() {
        initComponents();
        checkButtons();
        setLocationRelativeTo(null);//κεντράρισμα φόρμας
    }

        private void checkButtons() {//ενεργοποίηση κουμπιών
        selectedRow = ArtistTable.getSelectedRow();
        delArtist.setEnabled(selectedRow >= 0);
        editArtist.setEnabled(selectedRow >= 0);
        if (selectedRow >= 0) {
            artist = artistList.get(ArtistTable.convertRowIndexToModel(selectedRow));
        }        
    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("RadiostationPU").createEntityManager();
        artistQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Artist a");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(artistQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        newArtist = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        ArtistTable = new javax.swing.JTable();
        editArtist = new javax.swing.JButton();
        delArtist = new javax.swing.JButton();
        exit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Διαχείριση Καλλιτεχνών");
        setBackground(new java.awt.Color(204, 255, 255));
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Monotype Corsiva", 1, 18)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(153, 0, 51));
        jLabel1.setText("Π ί ν α κ α ς        Κ α λ λ ι τ ε χ ν ώ ν");

        newArtist.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        newArtist.setForeground(new java.awt.Color(153, 0, 51));
        newArtist.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Add.png"))); // NOI18N
        newArtist.setText("Δημιουργία ");
        newArtist.setPreferredSize(new java.awt.Dimension(50, 29));
        newArtist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newArtistActionPerformed(evt);
            }
        });

        ArtistTable.setBackground(java.awt.Color.lightGray);
        ArtistTable.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        ArtistTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        ArtistTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, ArtistTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastname}"));
        columnBinding.setColumnName("Επώνυμο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstname}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticname}"));
        columnBinding.setColumnName("Καλλιτεχνικό όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        ArtistTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ArtistTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(ArtistTable);

        editArtist.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        editArtist.setForeground(new java.awt.Color(153, 0, 51));
        editArtist.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Edit.png"))); // NOI18N
        editArtist.setText("Τροποποίηση");
        editArtist.setPreferredSize(new java.awt.Dimension(50, 29));
        editArtist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editArtistActionPerformed(evt);
            }
        });

        delArtist.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        delArtist.setForeground(new java.awt.Color(153, 0, 51));
        delArtist.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Delete.png"))); // NOI18N
        delArtist.setText("Διαγραφή");
        delArtist.setPreferredSize(new java.awt.Dimension(50, 29));
        delArtist.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delArtistActionPerformed(evt);
            }
        });

        exit.setFont(new java.awt.Font("Calibri", 1, 12)); // NOI18N
        exit.setForeground(new java.awt.Color(153, 0, 51));
        exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Log Out.png"))); // NOI18N
        exit.setText("Έξοδος");
        exit.setPreferredSize(new java.awt.Dimension(50, 29));
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(newArtist, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(editArtist, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addComponent(delArtist, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(28, 28, 28)
                .addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 664, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(173, 173, 173))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newArtist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(editArtist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(delArtist, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(exit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newArtistActionPerformed
        // ανοιγμα της φόρμας διαχείρισης καλλιτεχνών
       new NewOrModifyArtistForm(null,false).setVisible(true);
            thisFrame=this;
            thisFrame.setEnabled(false);
            thisFrame.dispose();
    }//GEN-LAST:event_newArtistActionPerformed

    private void ArtistTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ArtistTableMouseClicked
        // για την ενεργοποίηση
        checkButtons();
    }//GEN-LAST:event_ArtistTableMouseClicked

    private void editArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editArtistActionPerformed
        // όταν επιλέγει τροποποίηση
        int s=ArtistTable.getSelectedRow();              
        if (s>=0){
            Artist a = artistList.get(s);
            NewOrModifyArtistForm nmf = new NewOrModifyArtistForm(a,true);
            nmf.setVisible(true);
            nmf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            nmf.setVisible(true); 
            this.dispose();//kleisimo formas
          }
        else{
            JOptionPane.showMessageDialog(null, "Δεν επιλέξατε καλλιτέχνη", "Σφάλμα", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_editArtistActionPerformed

    private void delArtistActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delArtistActionPerformed
  //διαγραφή γκρουπ από βάση, σβήνω πρώτα τα αλμπουμ με loop και μετά το γκρουπ, δεν έπαιζε το cascade
        int s=ArtistTable.getSelectedRow();
        if (s>=0){           
            Artist a2del = artistList.get(s);
            if (JOptionPane.showConfirmDialog(null, "Είστε σίγουρος ότι θέλετε να διαγράψετε τον επιλεγμένο Καλλιτέχνη;", "Διαγραφή", JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
              if (!DBManager.getEm().getTransaction().isActive()){
            DBManager.getEm().getTransaction().begin();
        }
                try{
                    Artist a2del2= DBManager.getEm().createNamedQuery("Artist.findByArtistId", Artist.class).setParameter("artistId", a2del.getArtistId()).getSingleResult();
            
                    List listTodel= DBManager.getEm().createNamedQuery("Album.findByFkArtist", Album.class).setParameter("fkArtistId", a2del2).getResultList();
                    if (!listTodel.isEmpty()) { // σβήνω τα αλμπουμ των καλλιτεχνών
                        Iterator itr=listTodel.iterator();
                        while (itr.hasNext()){
                            Album al = (Album)itr.next();
                            DBManager.getEm().remove(al);
                                }
                     }
                    DBManager.getEm().remove(a2del2);
                    DBManager.getEm().getTransaction().commit();
                    artistList.remove(s);
                } catch (Exception e) {
                    e.printStackTrace();
                    DBManager.getEm().getTransaction().rollback();
                }
            }
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν επιλέξατε κάποιον καλλιτέχνη", "Σφάλμα", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_delArtistActionPerformed

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        // TODO add your handling code here:
         dispose();
    }//GEN-LAST:event_exitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListArtistForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListArtistForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JTable ArtistTable;
    public static java.util.List<Artist> artistList;
    private javax.persistence.Query artistQuery;
    private javax.swing.JButton delArtist;
    private javax.swing.JButton editArtist;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton newArtist;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
